package cn.aitrox.ry.util;

public class CodeUtil {

    public final static char[] BASE = {'1', '2', '3', '5', '6', '7', '8', '9','A', 'B', 'C', 'D', 'E', 'F'};

    public  final static String DEFAULT_KEY = "NULL";

    public synchronized static String generateShortCode(Long number, Integer arbitraryBase, int len) {

        StringBuilder result = new StringBuilder();

        if (number == null) {

            number = System.currentTimeMillis();

        }

        if (arbitraryBase == null) {

            arbitraryBase = 10;

        }

        if (arbitraryBase > BASE.length) {

            throw new IndexOutOfBoundsException("超过进制转换限制，最大" + BASE.length);

        }

        //余数
        int remainder = 0;

        //商
        long quotient;

        //当 商 = 0 时结束
        while ((quotient = number / arbitraryBase) != 0) {

            //取余
            remainder = (int) (number % arbitraryBase);

            result.insert(0, BASE[remainder]);

            number = quotient;

        }

        //最后取一次余

        remainder = (int) (number % arbitraryBase);

        result.insert(0, BASE[remainder]);

        int length = result.length();

        if (length < len) {

            for (int i = 0; i < (len - length); i++) {

                result.insert(0, BASE[0]);

            }

        } else if(length > len) {
            result.delete(len, length);
        }

        return result.toString();

    }

    public static String genShortCode(String key, int len) {
        if(null == key) {
            key = DEFAULT_KEY;
        }
        if(len < 1) {
            len = 1;
        }
        return generateShortCode(Long.valueOf(key.getBytes().hashCode()),BASE.length, len);
    }

    public static String genShortCode(int len) {
        return genShortCode(null,len);
    }


    public static String getNumberCode(int number, int len) {
        String numStr = number + "";
        if (numStr.length() != len) {
            int zeroNum = len - numStr.length();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < zeroNum; i++) {
                sb.append(0);
            }
            return sb.toString() + numStr;
        }
        return numStr;
    }
}
